package com.baizhi.lucene;

import com.baizhi.dao.ArticleDao;
import com.baizhi.entrty.Article;
import com.baizhi.util.LuceneUtil;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class LuceneServiceImpl implements LuceneService {

    @Autowired
    private ArticleDao ad;

    @Override
    public int addIndexs(List<Article> articles) throws IOException {
        List<Document> document = new ArrayList<>();
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
        FSDirectory open = FSDirectory.open(new File("D://lucene"));

        for (Article as : articles) {

                Document document1 = new Document();
                document1.add(new StringField("articleId",as.getArticleId()+"", Field.Store.YES));
                document1.add(new StringField("articleName",as.getArticleName().toString(), Field.Store.YES));
                document1.add(new TextField("articleImage",as.getArticleImage().toString(), Field.Store.YES));
                document1.add(new TextField("articleContent",as.getArticleContent().toString(), Field.Store.YES));
                document.add(document1);

        }
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.addDocuments(document);
        } catch (IOException e) {
            e.printStackTrace();
        }
        LuceneUtil.commit(indexWriter);

        return 0;
    }

    @Override
    public boolean addIndexOne(Article article){
        Document document = new Document();
        document.add(new StringField("articleImage",article.getArticleImage(), Field.Store.YES));
        document.add(new TextField("articleName",article.getArticleName(), Field.Store.YES));
        document.add(new TextField("articleContent",article.getArticleContent(), Field.Store.YES));
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();

        try {
            indexWriter.addDocument(document);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }
    }

    @Override
    public boolean deleteAllIndex() {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();

        try {
            indexWriter.deleteAll();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }
    }

    @Override
    public boolean deleteOne(Article article) {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteDocuments(new Term("articeId",article.getArticleId()+""));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }
    }

    @Override
    public boolean updateOne(Article article) {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        Document document = new Document();

        document.add(new StringField("articleId",article.getArticleId()+"", Field.Store.YES));
        document.add(new StringField("articleName",article.getArticleName(), Field.Store.YES));
        document.add(new TextField("articleContent",article.getArticleContent(), Field.Store.YES));
        try {
            indexWriter.updateDocument(new Term("articleId",article.getArticleId()+""),document);
            return  true;
        } catch (IOException e) {
            e.printStackTrace();
        return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }

    }

    @Override
    public List<Article> queryByKeyword(String keyword)throws IOException, InvalidTokenOffsetsException {

        //定义分词器规则
        SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
        //获取分词结果
        Query query = LuceneUtil.getQuery(keyword);
        QueryScorer queryScorer = new QueryScorer(query);
        //创建高亮器
        Highlighter highlighter = new Highlighter(htmlFormatter,queryScorer);


        IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher();
        TopDocs topDocs=null;
        ArrayList<Article> articleList = new ArrayList<>();
        try {
            topDocs= indexSearcher.search(query, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        for (ScoreDoc scoreDoc:scoreDocs) {
            int doc = scoreDoc.doc;
            Document document=null;
            try {
                document= indexSearcher.doc(doc);
            } catch (IOException e) {
                e.printStackTrace();
            }

            String articleId = document.get("articleId");
            int parseInt = Integer.parseInt(articleId);

            String articleName = document.get("articleName");
            String articleImage = document.get("articleImage");
            String articleContent = document.get("articleContent");

            articleName = highlighter.getBestFragment(LuceneUtil.analyzer, "articleName", articleName);
            articleContent = highlighter.getBestFragment(LuceneUtil.analyzer, "articleContent", articleContent);

            Article article = new Article();
            article.setArticleId(parseInt);
            article.setArticleName(articleName);
            article.setArticleContent(articleContent);
            article.setArticleImage(articleImage);
            articleList.add(article);
        }
        return articleList;
    }

    @Override
    public boolean resetIndexDB() {

        try {
            //先删除
            boolean b=deleteAllIndex();
            //再添加
            List<Article> aticleList = ad.showArticle();
            addIndexs(aticleList);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
